import React, { useState } from 'react';
import styled from '@emotion/styled';
import { useDispatch, useSelector } from 'react-redux';
import { setScreenStream } from '@/store/reducers/stream';
import Icon from '@/components/Icon';
import { useTranslation } from 'react-i18next';
import { sendCustomeizeMessage } from '@/utils/lib';
// const arrowIcon = require('../../assets/img/arrow.png');

interface FooterProps {
	sendFreezeFrameImage?: (image: string) => void;
	clientId?: string;
	videoId: string;
	width: number;
	height: number;
}
const IconSvg = styled.span`
	display: flex;
	padding: 0 4px;
	vertical-align: middle;
    width: 36px;
    height: 30px;
`;
const Footer = (props: FooterProps) => {
	const { t } = useTranslation();
	const { width, height, clientId, videoId } = props;
	// const { screenStreams } = useSelector((state: any) => state);
	const [activeIndex, setActiveIndex] = useState(0);
	const [isFreezeFrame, setIsFreezeFrame] = useState(false); // 是否定格画面
	const [isFlag, setIsFlag] = useState(false); // 是否正在操作中
	const dispatch = useDispatch();
	const [tools, setTools] = useState([
		{
			id: 1,
			desc: '',
			mode: 'pen',
			icon: 'icon-widget-qianbi'
		},
		{
			id: 2,
			desc: '',
			mode: 'remove',
			icon: 'icon-widget-xiangpi'
		},
		{
			id: 3,
			desc: '',
			mode: 'line',
			icon: 'icon-widget-zhixian'
		},
		{
			id: 4,
			desc: '',
			mode: 'arrow',
			icon: 'icon-widget-arrow-line' // <ArrowRightOutlined />
		},
		{
			id: 5,
			desc: '',
			mode: 'square',
			icon: 'icon-widget-fang'
		},
		{
			id: 6,
			desc: '',
			mode: 'circle',
			icon: 'icon-widget-yuan'
		},
		{
			id: 7,
			desc: '',
			mode: 'text',
			icon: 'icon-widget-wenzi'
		}
	]);

	const toolClick = (item: any) => {
		dispatch(setScreenStream({ tool: item }));
	};

	const freezeFrameImg = async () => {
		if (isFlag) {
			console.log('操作正在进行中，请稍后再试。');
			return;
		}
		if (!isFreezeFrame) {
			// 开启画面定格，截图画面，并通知访客
			try {
				setIsFlag(true);
				const imageBase64 = (await snapshot()) as string;
				let messageData = {
					businessType: `customer-view-freeze-frame`,
					clientId,
					imageBase64
				};
				await sendCustomeizeMessage(messageData, clientId!);
				// 首先获取父容器
				const parentContainer = document.getElementById('customer-view-mark-container');
				// 创建一个新的div元素
				const container = document.createElement('div');
				container.id = 'freeze-frame-image';
				container.setAttribute('class', 'freeze-frame-image');
				parentContainer!.appendChild(container); // 将div添加到父容器中
				// 创建一个新的img元素
				const imgElement = document.createElement('img') as HTMLImageElement;
				imgElement.src = imageBase64; //
				imgElement!.id = 'freeze-frame-image-element';
				imgElement.style.width = '100%'; // 设置图片宽度为100%
				imgElement.style.height = '100%'; // 设置图片高度为100%
				// 将img元素添加到div中
				container.appendChild(imgElement);
				setIsFreezeFrame(true);
			} catch (error) {
				console.log('freeze-frame-customer-view-mark error', error);
			} finally {
				setIsFlag(false);
			}
		} else {
			setIsFlag(true);
			try {
				let messageData = {
					businessType: `stop-customer-view-freeze-frame`,
					clientId
				};
				await sendCustomeizeMessage(messageData, clientId!);
				const container = document.getElementById('freeze-frame-image');
				const parentContainer = document.getElementById('customer-view-mark-container');
				parentContainer && container && parentContainer.removeChild(container);
				setIsFreezeFrame(false);
			} catch (error) {
				console.log('cancel freeze frame error', error);
			} finally {
				setIsFlag(false);
			}
		}
	};

	const snapshot = () => {
		return new Promise(async (resolve, reject) => {
			try {
				let canvas = document.createElement('canvas');
				canvas.width = width;
				canvas.height = height;
				let ctx = canvas.getContext('2d');
				const video = document.getElementById(videoId + '-mark') as HTMLVideoElement;
				// 计算视频的缩放比例
				function getVideoScale(video: HTMLVideoElement, containerWidth: number, containerHeight: number) {
					const videoAspectRatio = video.videoWidth / video.videoHeight;
					const containerAspectRatio = containerWidth / containerHeight;
					let scale = 1;
					if (videoAspectRatio > containerAspectRatio) {
						// 视频比容器宽，需要按宽度缩放
						scale = containerWidth / video.videoWidth;
					} else {
						// 视频比容器高，需要按高度缩放
						scale = containerHeight / video.videoHeight;
					}
					return scale;
				}
				// 绘制视频到画布上，保持宽高比
				function drawVideoToCanvas(video: HTMLVideoElement, canvas: HTMLCanvasElement) {
					const scale = getVideoScale(video, canvas.width, canvas.height);
					const newWidth = video.videoWidth * scale;
					const newHeight = video.videoHeight * scale;
					const x = (canvas.width - newWidth) / 2;
					const y = (canvas.height - newHeight) / 2;
					ctx!.drawImage(video, x, y, newWidth, newHeight);
				}
				drawVideoToCanvas(video, canvas);
				resolve(canvas.toDataURL('image/png'));
				// 释放绘图上下文和canvas引用
				ctx = null;
				canvas = null!;
			} catch (error) {
				console.log('snapShot error', error);
				reject(error);
			}
		});
	};

	return (
		<ul className="customer-view-mark-footer ">
			{tools.map((item, index) => (
				<li
					className={activeIndex === index ? 'active' : ''}
					key={item.id}
					onClick={() => {
						toolClick(item);
						setActiveIndex(index);
					}}
				>
					{item.mode == 'arrow' && <IconSvg className="widget-icon">
						<svg className="widget-icon">
							<use xlinkHref={'#icon-widget-arrow-line'}></use>
						</svg>
					</IconSvg>}
					{item.mode !== 'arrow' && <Icon classname={item.icon}></Icon>}
				</li>
			))}
			<li
				className="end-screen-btn"
				onClick={() => {
					freezeFrameImg();
				}}
			>
				{!isFreezeFrame ? t('freeze-frame') : t('cancel-freeze-frame')}
			</li>
			<canvas id="canvas-capture" className="canvas-capture"></canvas>
		</ul>
	);
};

export default Footer;
